﻿using System.Collections.Generic;
using System.Linq;
using Basic4Net.Entities;
using Basic4Net.BusinessRules.View;
using System.Data.Objects;
using Microsoft.Data.Extensions;
using System;
 

namespace Basic4Net.BusinessRules
{
    public class PostRelation : BaseBR
    {
        private static PostRelation _postRelationInstance;
        public static PostRelation PostRelationInstance
        {
            get { return _postRelationInstance ?? (_postRelationInstance = new PostRelation()); }
        }



        public IList<TeachPostEntity> GetTeachInfoByPost(int startAt,int step,int? postId,string teachCode, string schoolMark,ref int count,int? userId)
        {
            using (DBEntities db = new DBEntities())
            {
                var teachtemp = from t in db.TEACHERINFO
                                join pr in db.t_PostRelation on t.RID equals pr.TeacherID into temp
                                from r in temp.DefaultIfEmpty() 
                                where (t.SCHOOLMARK == schoolMark) &&
                                (t.ISEFFECT ==1) && 
                                (String.IsNullOrEmpty(teachCode) ? true : (t.TEACHCODE.Contains(teachCode) || t.TEACHNAME.Contains(teachCode))) &&
                                (userId.HasValue?t.RID == userId:true )
                                select new
                                {
                                    PostId = r.PostID, 
                                    TeacherId = t.RID, 
                                    TeachName = t.TEACHNAME,
                                    TeachCode = t.TEACHCODE,
                                    Sexy = t.SEXY == null?string.Empty:t.SEXY== 0 ? "男" : "女",
                                    BirthDay = t.BIRTHDAY
                                };
                string s = teachtemp.ToTraceString();
               var post = (from p in db.t_Post
                           where p.RID == postId
                           select p);

               s = post.ToTraceString();
               IEnumerable<TeachPostEntity> teacherList = from r1 in teachtemp
                                                          join r2 in post on r1.PostId equals r2.RID into temp
                                                          from r in temp.DefaultIfEmpty()
                                                          where postId.HasValue ? (r1.PostId == postId) : (r1.PostId == null || r1.PostId <= 0)
                                                          && r1.TeachCode != "admin"
                                                          orderby r1.TeachCode descending
                                                          select new TeachPostEntity
                                                          {
                                                              PostID = r1.PostId == null ? -1 : r1.PostId,
                                                              PostName = r.PostName == null ? string.Empty : r.PostName,
                                                              TeacherID = r1.TeacherId == null ? 0 : r1.TeacherId,
                                                              TeachName = r1.TeachName == null ? string.Empty : r1.TeachName,
                                                              TeachCode = r1.TeachCode == null ? string.Empty : r1.TeachCode,
                                                              Sexy = r1.Sexy,
                                                              BirthDay = r1.BirthDay
                                                          };


                count = teacherList.Count();
                List<TeachPostEntity> list = null;
               // list = teacherList.ToList<TeachPostEntity>();
                 
                list = teacherList.Skip(startAt).Take(step).ToList<TeachPostEntity>();
                
                return list;
            }
        }

        public IList<TeachPostEntity> GetTeachInfoByPost(int startAt, int step, int? postId, string teachCode, string schoolMark, ref int count)
        {
            using (DBEntities db = new DBEntities())
            {
                var teachtemp = from t in db.TEACHERINFO
                                join pr in db.t_TeacherRelation on t.RID equals pr.TeacherID into temp
                                from r in temp.DefaultIfEmpty()
                                where (t.SCHOOLMARK == schoolMark) &&
                                (t.ISEFFECT == 1) &&
                                (String.IsNullOrEmpty(teachCode) ? true : (t.TEACHCODE.Contains(teachCode) || t.TEACHNAME.Contains(teachCode))) 
                              
                                select new
                                {
                                    PostId = r.TypeID,
                                    TeacherId = t.RID,
                                    TeachName = t.TEACHNAME,
                                    TeachCode = t.TEACHCODE,
                                    Sexy = t.SEXY == null ? string.Empty : t.SEXY == 0 ? "男" : "女",
                                    BirthDay = t.BIRTHDAY
                                };
                //string s = teachtemp.ToTraceString();
                //var post = (from p in db.t_Post
                //            where p.RID == postId
                //            select p);

                //s = post.ToTraceString();
                IEnumerable<TeachPostEntity> teacherList = from r1 in teachtemp
                                                           //join r2 in post on r1.PostId equals r2.RID into temp
                                                           join r2 in db.t_TeacherType on r1.PostId equals r2.RID into temp
                                                           from r in temp.DefaultIfEmpty()
                                                           //where postId.HasValue ? (r1.PostId == postId) : (r1.PostId == null || r1.PostId <= 0)
                                                           where (postId.HasValue ? (postId == 0 ? true : r1.PostId == postId) : (r.RID == null))
                                                           && r1.TeachCode != "admin"
                                                           //orderby r1.TeachCode descending
                                                           orderby r1.TeachCode
                                                           select new TeachPostEntity
                                                           {
                                                               PostID = r1.PostId == null ? -1 : r1.PostId,
                                                               PostName = r.TypeName == null ? string.Empty : r.TypeName,
                                                               TeacherID = r1.TeacherId == null ? 0 : r1.TeacherId,
                                                               TeachName = r1.TeachName == null ? string.Empty : r1.TeachName,
                                                               TeachCode = r1.TeachCode == null ? string.Empty : r1.TeachCode,
                                                               Sexy = r1.Sexy,
                                                               BirthDay = r1.BirthDay
                                                           };


                count = teacherList.Count();
                List<TeachPostEntity> list = null;
                // list = teacherList.ToList<TeachPostEntity>();

                list = teacherList.Skip(startAt).Take(step).ToList<TeachPostEntity>();

                return list;
            }
        }

        public bool UpdateTeachPostRelation(int[] arrId,int postId,int[] oldPostId,string schoolMark)
        {
            bool result = true;
            using (DBEntities db = new DBEntities())
            {
                for (int index = 0; index < arrId.Length;index++)
                {
                    if (arrId[index] <= 0 || oldPostId[index]<=0)
                        continue;

                    int tid = arrId[index];
                    int pid = oldPostId[index];
                    var tempOld = from b in db.t_PostRelation
                                  where b.TeacherID == tid && b.SchoolMark == schoolMark && b.PostID == pid
                                  select b;


                    //var temp = from b in db.t_PostRelation
                    //           where b.TeacherID == teacherId && b.SchoolMark == schoolMark && b.PostID == postId
                    //           select b;
                    try
                    {
                        foreach (t_PostRelation tPostRelation in tempOld)
                        {
                            db.DeleteObject(tPostRelation);
                        }

                        //if (temp.Count() == 0)
                        if (postId!=-1)
                        {
                            var temp = from b in db.t_PostRelation
                                       where b.TeacherID == tid && b.SchoolMark == schoolMark && b.PostID == postId
                                       select b;
                            if (temp.Count() == 0)
                            {
                                t_PostRelation item = new t_PostRelation();
                                item.PostID = postId;
                                item.SchoolMark = schoolMark;
                                item.TeacherID = arrId[index];

                                db.AddTot_PostRelation((item));
                            }
                        }

                        db.SaveChanges(); //存在修改
                    }
                    catch (Exception)
                    {
                        result = false;
                    }
                }
            }
            return result;
        }


        public bool AddTeachPostRelation(int[] arrId,int postId,string schoolMark)
        {
            bool result = true;
            if (arrId.Count() == 0 || postId <= 0)
                return false;
            using (DBEntities db = new DBEntities())
            {
                foreach (int teacherId in arrId)
                {
                    if(teacherId <= 0)
                        continue;
                    
                    var temp = from b in db.t_PostRelation
                               where b.TeacherID == teacherId && b.SchoolMark == schoolMark && b.PostID == postId
                               select b;

                    if (temp.Count() == 0) 
                    {
                        t_PostRelation item = new t_PostRelation();
                        item.PostID = postId;
                        item.SchoolMark = schoolMark;
                        item.TeacherID = teacherId;

                        db.AddTot_PostRelation((item));
                        try
                        {
                            db.SaveChanges(); //不存在插入
                        }
                        catch (Exception)
                        {
                            result = false;
                        }

                    }

                }
                return result;
            }

        }


        /// <summary>
        /// 修改车辆
        /// </summary>
        /// <param name="entity">车辆实体</param>
        /// <param name="msg">错误信息</param>
        /// <returns>是否成功</returns>
        public bool Delete(t_PostRelation entity, ref string msg)
        {
            bool result = true;

            using (DBEntities db = new DBEntities())
            {
                var list = from post
                           in db.t_PostRelation
                           where post.TeacherID == entity.TeacherID 
                           && post.SchoolMark == entity.SchoolMark
                           && post.PostID == entity.PostID
                          
                           select post;
                foreach (t_PostRelation tempPost in list.ToList<t_PostRelation>())
                {
                    try
                    {
                        db.DeleteObject(tempPost);
                        db.SaveChanges();
                    }
                    catch
                    {
                        msg = "操作失败！";
                        result = false;
                    }
                }
                return result;
            }
        }


    } 
}
